package com.example.demo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @Author songxulin
 * @Date 2019/8/21 14:51
 **/
public class AtomicIntegerDemo {
    private static AtomicInteger atomicInteger = new AtomicInteger(0);
    private static volatile  Integer integer=new Integer(0);
    private static final int NUM=100;
    private static CountDownLatch latch = new CountDownLatch(NUM);
    private static ExecutorService threadPool = Executors.newFixedThreadPool(NUM);
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i=0;i<NUM;i++){
            threadPool.submit(new AtomicIntegerRunner());
        }
        try {
            threadPool.shutdown();
            threadPool.awaitTermination(1, TimeUnit.MINUTES);
//            latch.await();
        }catch (Exception e){

        }
        System.out.println("用时："+(System.currentTimeMillis()-start));
        System.out.println(integer);
        System.out.println(atomicInteger);
    }

    private static class NormalRunner implements Runnable{

        @Override
        public void run() {
            for (int i=0;i<100000;i++) {
                integer++;
            }
            latch.countDown();
        }
    }


    private static class SynchronizedRunner implements Runnable{

        @Override
        public void run() {
            for (int i=0;i<100000;i++) {
                synchronized (AtomicIntegerDemo.class){
                    integer++;
                }
            }
//            latch.countDown();
        }
    }



    private static class AtomicIntegerRunner implements Runnable{

        @Override
        public void run() {
            for (int i=0;i<100000;i++) {
                int i1 = atomicInteger.incrementAndGet();
            }
            latch.countDown();
        }
    }
}
